#
# test01.py
#
# Copyright (C) 2013 Robert Buj Gelonch
# Copyright (C) 2013 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys

from numpy import abs
from numpy import angle
from numpy import cos
from numpy import sin
from numpy.fft import rfft
from numpy.fft import irfft
from pylab import figure
from pylab import plot
from pylab import show
from scipy.io.wavfile import read

def module_phase(spectrum):
    return abs(spectrum), angle(spectrum)

def test01(f1):
    print "test01.py"
    print
    #--------------------------------------------------------------
    # Read data and obtain basic attributes
    #--------------------------------------------------------------
    [sample_rate_x, x] = read(f1)
    #--------------------------------------------------------------
    # Obtain module and phase
    #--------------------------------------------------------------
    m_x, p_x = module_phase(rfft(x[1:5 * 8000]))
    #--------------------------------------------------------------
    # Signal reconstruction IFFT
    #--------------------------------------------------------------
    fig = figure(num=None, figsize=(12, 9), dpi=80, facecolor='w', edgecolor='k')

    rX = [complex(m_x[idx] * cos(p_x[idx]), m_x[idx] * sin(p_x[idx])) for idx in range(len(m_x))]
    rx = irfft(rX)
    plot(rx, 'r', label="reconstruction")
    plot(x, 'b', label="original")

    show()


def main(argv):
    f1 = '../media/fem1.wav'
    test01(f1)

if __name__ == "__main__":
    main(sys.argv[1:])
    print "Done"